//
//  FMDBManager.m
//  WGDemo
//
//  Created by T on 14-3-26.
//  Copyright (c) 2014年 PK. All rights reserved.
//

#import "FMDBManager.h"

static FMDBManager* manager = nil;
@implementation FMDBManager
+ (FMDBManager *)sharedManager{
    if (manager == nil) {
        manager = [[FMDBManager alloc] init];
    }
    return manager;
}
+ (id)allocWithZone:(struct _NSZone *)zone{
    if (manager == nil) {
        manager = [super allocWithZone:zone];
        return manager;
    }
    return nil;
}
- (id)retain{
    return manager;
}
- (id)autorelease{
    return manager;
}
- (oneway void)release{

}
- (id)init{
    if (self = [super init]) {
        NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/user.sqlite"];
        _db = [[FMDatabase alloc] initWithPath:path];
        BOOL res = [_db open];
        if (res == NO) {
            NSLog(@"打开失败");
            return self;
        }
        
        //创建User表
        res = [_db executeUpdate:@"create table if not exists USER(uid integer primary key autoincrement,name,menpai)"];
        if (res == NO) {
            NSLog(@"创建User表失败");
        }
    }
    return self;
}
//添加一个用户
- (BOOL)addUser:(DingSh*)user{
    //user.name user.menpai user.wugong
    BOOL res = [_db executeUpdate:@"insert into USER(name,menpai) values(?,?)",user.name,user.tel];
    if (res == NO)
    {
        NSLog(@"插入用户失败");
        return NO;
    }
    return YES;
}
//拿到插入用户的uid
- (int)getUserid{
    FMResultSet* set = [_db executeQuery:@"select * from USER order by uid desc limit 1"];
    [set next];
    int uid = [set intForColumn:@"uid"];
    return uid;
}
//得到全部用户
- (NSArray*)getAllUsers{
    NSMutableArray* array = [NSMutableArray array];
    FMResultSet* set = [_db executeQuery:@"select * from USER"];
    while ([set next]) {
       // int uid = [set intForColumn:@"uid"];
        DingSh* user = [[DingSh alloc] init];
        user.name = [set stringForColumn:@"name"];
        user.tel = [set stringForColumn:@"menpai"];
        if(user.name ==nil)
        {
            user.name =@"位置联系人";
        }
        if(user.tel==nil)
        {
            user.tel=@"";
        }
        [array addObject:user];
        [user release];
    }
    return array;
}
@end
